/**
 * @param {number} n
 * @return {number[][]}
 */
var generateMatrix = function (n) {
    let arr = new Array(n).fill(0)
    arr = arr.map(item => {
        return new Array(n).fill(0)
    })

    let dir = -1
    let dirList = [[0, 1], [1, 0], [0, -1], [-1, 0]]
    function direction() {
        dir++
        return dirList[dir % 4]
    }
    let i = 0;
    let j = 0;
    let total = n * n
    let count = 1
    let d = direction()
    while (count <= total) {
        
        if((i + d[0])<0||(i + d[0])>=n||(j + d[1]<0||(j + d[1])>=n)){
            d = direction()
        }
        
        arr[i][j] = count

        
        i = i + d[0]
        j = j + d[1]
        if(arr[i]&&arr[i][j]&&arr[i][j]>0){
            i = i - d[0]
            j = j - d[1]
            d = direction()
            i = i + d[0]
            j = j + d[1]
        }

        count++
    }

    return arr
};
console.log(generateMatrix(5));
